package controllers.record;

import hprose.HproseClinetService;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ning.http.util.DateUtil;

import component.UserBis;
import constants.APIConstants;
import constants.Constants;
import controllers.common.filter.BaseFilter;
import controllers.login.LoginAction;
import play.Logger;
import play.mvc.Controller;
import utils.convert.Convert;
import utils.date.DateUtils;
import utils.file.DownExcel;
import utils.logs.LogsUtils;

/**
 * 报表
 * 
 * @ClassName: RecordAction
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chasel 641243343@qq.com
 * @date 2016年3月18日 下午2:47:44
 *
 */
public class RecordAction extends BaseFilter {

	public static void getCutterUseRecordIndex() {
		render();
	}

	/**
	 * 查询每日刀具计划用量及实际领用量
	 * 
	 * @Title: getCutterUseRecordInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param 设定文件
	 * @return void 返回类型
	 * @author chasel 641243343@qq.com
	 * @throws
	 */
	public static void getCutterUseRecordInfo() {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id", UserBis.currUser());
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		String json = HproseClinetService.synCall(
				APIConstants.CSTATMI_GETCUTTERUSESTATISTCS, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject obj = JSONObject.parseObject(json);
		JSONArray arr = obj.getJSONArray("data");
		renderJSON(arr);
	}

	/**
	 * 每日刀具计划用量及实际领用量 导出Excel
	 * 
	 * 2016年6月7日 下午5:53:52
	 * 
	 * @auth liqi
	 */
	public static void downCutterUseRecord() {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id", UserBis.currUser());
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		String res = HproseClinetService.synCall(
				APIConstants.CSTATMI_GETCUTTERUSESTATISTCS, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject json = JSONObject.parseObject(res);
		List<Map<String, Object>> list = (List<Map<String, Object>>) json
				.get("data");
		List<Map<String, Object>> listData = new ArrayList<Map<String, Object>>();
		// 时间列表
		List dateList = new ArrayList();
		// 规格列表
		List materialIdList = new ArrayList();
		StringBuffer dateHead = new StringBuffer();
		StringBuffer dateHeadData = new StringBuffer();

		dateHead.append("编码:规格:简称:状态");
		dateHeadData.append("materialId:cutter_specs:simple_specs_cust:pr");
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map2 = list.get(i);
			// 不包含该时间 添加
			if (!dateList.contains(map2.get("date"))) {
				dateList.add(map2.get("date"));
			}
			// 不包含该规格 添加
			if (!materialIdList.contains(map2.get("material_id"))) {
				materialIdList.add(map2.get("material_id"));
			}
		}
		Collections.sort(materialIdList);
		Collections.sort(dateList);
		for (int j = 0; j < dateList.size(); j++) {
			String date = (String) dateList.get(j);
			dateHead.append(":" + date);
			dateHeadData.append(":num" + j);
		}
		for (int i = 0; i < materialIdList.size(); i++) {
			Map<String, Object> map3 = new HashMap<String, Object>();
			String materialIds = materialIdList.get(i).toString();
			map3.put("materialId", materialIds);
			map3.put("pr", "计划用量");
			// 获取刀具编码
			for (int k = 0; k < list.size(); k++) {
				Map<String, Object> map2 = list.get(k);
				if (materialIds.equals(map2.get("material_id"))) {
					map3.put("cutter_specs", map2.get("cutter_specs"));
					map3.put("simple_specs_cust", map2.get("simple_specs_cust"));
					break;
				}
			}

			// 循环时间
			for (int j = 0; j < dateList.size(); j++) {
				String date = (String) dateList.get(j);
				// 获取数量
				for (int x = 0; x < list.size(); x++) {
					Map<String, Object> map2 = list.get(x);
					if (date.equals(map2.get("date"))
							&& 1 == Integer.parseInt(map2.get("type")
									.toString())
							&& materialIds.equals(map2.get("material_id"))) {
						map3.put("num" + j,
								Integer.parseInt(map2.get("num").toString()));
						break;
					}
					if (x == list.size() - 1) {
						map3.put("num" + j, "");
					}
				}
			}
			// 添加 计划用量
			listData.add(map3);

			Map<String, Object> map4 = new HashMap<String, Object>();
			map4.put("materialId", materialIdList.get(i));
			map4.put("pr", "实际领用");
			// 获取刀具编码
			for (int k = 0; k < list.size(); k++) {
				Map<String, Object> map2 = list.get(k);
				if (materialIds.equals(map2.get("material_id"))) {
					map4.put("cutter_specs", map2.get("cutter_specs"));
					map4.put("simple_specs_cust", map2.get("simple_specs_cust"));
					break;
				}
			}
			// 循环时间
			for (int j = 0; j < dateList.size(); j++) {
				String date = (String) dateList.get(j);
				// 获取数量
				for (int x = 0; x < list.size(); x++) {
					Map<String, Object> map2 = list.get(x);
					if (date.equals(map2.get("date"))
							&& 2 == Integer.parseInt(map2.get("type")
									.toString())
							&& materialIds.equals(map2.get("material_id"))) {
						map4.put("num" + j,
								Integer.parseInt(map2.get("num").toString()));
						break;
					}
					if (x == list.size() - 1) {
						map4.put("num" + j, "");
					}
				}
			}
			// 添加 实际领用
			listData.add(map4);
		}

		Map<String, Object> map5 = new HashMap<String, Object>();
		map5.put("materialId", "");
		map5.put("cutter_specs", "");
		map5.put("simple_specs_cust", "SUM");
		map5.put("pr", "计划用量合计");
		// 循环时间
		for (int j = 0; j < dateList.size(); j++) {
			int planNum = 0;
			// 获取数量
			for (int x = 0; x < listData.size(); x++) {
				Map<String, Object> map2 = listData.get(x);
				if ("计划用量".equals(map2.get("pr"))) {
					if (StringUtils.isNotBlank(map2.get("num" + j).toString())) {
						planNum = planNum
								+ Integer.parseInt(map2.get("num" + j)
										.toString());
						continue;
					}
				}
			}
			map5.put("num" + j, planNum);
		}
		listData.add(map5);

		Map<String, Object> map6 = new HashMap<String, Object>();
		map6.put("materialId", "");
		map6.put("cutter_specs", "");
		map6.put("simple_specs_cust", "SUM");
		map6.put("pr", "实际领用合计");
		// 循环时间
		for (int j = 0; j < dateList.size(); j++) {
			int actualNum = 0;
			// 获取数量
			for (int x = 0; x < listData.size(); x++) {
				Map<String, Object> map2 = listData.get(x);
				if ("实际领用".equals(map2.get("pr"))) {
					if (StringUtils.isNotBlank(map2.get("num" + j).toString())) {
						actualNum = actualNum
								+ Integer.parseInt(map2.get("num" + j)
										.toString());
						continue;
					}
				}
			}
			map6.put("num" + j, actualNum);
		}
		listData.add(map6);

		HSSFWorkbook wb = DownExcel.downExcel("计划用量与实际领用量列表",
				dateHead.toString(), dateHeadData.toString(), listData);
		// 生成文件名
		String fileName = "CutterUseRecord"
				+ DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + ".xls";
		try {
			response.setContentTypeIfNotSet("application/vnd.ms-excel");
			response.setHeader("content-disposition", "attachment;filename="
					+ URLEncoder.encode(fileName, "GB2312"));
			OutputStream out = response.out;
			wb.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			list.clear();
			listData.clear();
		}

	}

	public static void getCutterUseProjectRecordIndex() {
		render();
	}

	public static void getCutterUseProjectRecordInfo() {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id", UserBis.currUser());
		map.put("date", params.get("date"));
		String json = HproseClinetService.synCall(
				APIConstants.CSTATMI_GETCUTTERUSEPROJECTSTATISTCS, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject obj = JSONObject.parseObject(json);
		JSONArray arr = obj.getJSONArray("data");
		renderJSON(arr);
	}

	public static void getPlanCompleteDetailIndex() {
		render();
	}

	/**
	 * 项目详细排配
	 * 
	 * @Title: getPlanCompleteDetailInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param 设定文件
	 * @return void 返回类型
	 * @author chasel 641243343@qq.com
	 * @throws
	 */
	public static void getPlanCompleteDetailInfo() {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id", UserBis.currUser());
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		String json = HproseClinetService.synCall(
				APIConstants.PPMSI_GETPLANCOMPLETEDETAIL, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject obj = JSONObject.parseObject(json);
		JSONArray arr = obj.getJSONArray("data");
		renderJSON(arr);
	}

	public static void chartsIndex() {
		String res = "";
		Map<String, Object> useNumParam = new HashMap<String, Object>();
		Object[] arguments = new Object[] { useNumParam };
		useNumParam.put("customer_id", UserBis.currUser());
		useNumParam.put("date", DateUtils.getCurrentDateTimeSimple());
		useNumParam.put("isPage", Constants.DATAISPAGE_NO);
		res = HproseClinetService.synCall(APIConstants.SMSI_HOMESTATISTICSLIST,
				arguments, APIConstants.CUSTOMER_HOST,
				APIConstants.CUSTOMER_PORT);
		String plans = HproseClinetService.synCall(
				APIConstants.PPMSI_GETPRODUCTIONPLANLIST, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String cutterspesc = HproseClinetService.synCall(
				APIConstants.CSMI_GETCUTTERSPECS, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String projects = HproseClinetService.synCall(
				APIConstants.PJMSI_GETPROJECT, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		Logger.info("cutterspecs-->" + cutterspesc);
		String useNum = "0";
		String useCount = "0";
		String recNum = "0";
		String recCount = "0";
		if ("服务不可用".equals(res) || "服务不可用".equals(cutterspesc)) {
			renderArgs.put("error", "-1");
			LoginAction.login();
		}
		JSONObject custCutters = JSONObject.parseObject(cutterspesc);
		JSONObject projectsJSON = JSONObject.parseObject(projects);
		JSONObject plansJSON = JSONObject.parseObject(plans);
		JSONObject custCutterSupps = JSONObject.parseObject(HproseClinetService
				.synCall(APIConstants.CSMI_GETCUTTERSPECSANDSUPPNAME,
						arguments, APIConstants.CUSTOMER_HOST,
						APIConstants.CUSTOMER_PORT));
		JSONObject jsonStr = JSONObject.parseObject(res);
		JSONArray arr = jsonStr.getJSONArray("data");
		useNum = arr.getJSONObject(0).get("useNum") + "";
		useCount = arr.getJSONObject(0).get("useCount") + "";
		recNum = arr.getJSONObject(0).get("recNum") + "";
		recCount = arr.getJSONObject(0).get("recCount") + "";
		render(useNum, useCount, recNum, recCount, custCutters,
				custCutterSupps, projectsJSON, plansJSON);
	}

	/**
	 * 项目刀具使用饼图
	 */
	public static void getProjectByPeriodQuerySum() {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("project_id", params.get("project_id"));
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		String json = HproseClinetService.synCall(
				APIConstants.SMSI_PROJECTBYPERIODQUERYSUM, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject obj = JSONObject.parseObject(json);
		JSONArray arr = obj.getJSONArray("data");
		renderJSON(arr);

	}

	/**
	 * 刀具寿命页面
	 * 
	 * 2016年7月19日 上午11:05:50
	 * 
	 * @auth liqi
	 */
	public static void getCutterLifeIndex() {
		JSONObject projects = new JSONObject();
		String state = "'0','1','2'";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("isPage", Constants.DATAISPAGE_NO);
		map.put("states", "0,1,2");
		Object[] arguments = new Object[] { map };
		String res = HproseClinetService.synCall(
				APIConstants.PJMSI_GETPROJECT, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		projects = JSONObject.parseObject(res);
		JSONArray projectArr = projects.getJSONArray("data");
		for (int i = 0; i < projectArr.size(); i++) {
			JSONObject cutter = projectArr.getJSONObject(i);
			cutter.put("id", cutter.get("project_id"));
			cutter.put("value", cutter.get("project_name"));
		}
		render(projects);
	}

	/**
	 * 查看刀具寿命阶梯数据
	 * 
	 * 2016年7月19日 下午2:35:55
	 * 
	 * @auth liqi
	 */
	public static void getCutterLife() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("material_id", params.get("material_id"));
		map.put("project_id", params.get("project_id"));
		map.put("startDate", params.get("startDate"));
		map.put("endDate", params.get("endDate"));
		Object[] arguments = new Object[] { map };
		String cutterspesc = HproseClinetService.synCall(
				APIConstants.CSMI_GETCUTTERLIFE, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject json = JSONObject.parseObject(cutterspesc);
		String res = json.getString("data");
		renderJSON(res);
	}

	/**
	 * 添加使用寿命区间
	 * 
	 * 2016年7月15日 上午9:38:32
	 * 
	 * @auth liqi
	 */
	public static void addCutterSpecsInterval() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("data", params.get("reData"));
		map.put("material_id", params.get("material_id"));
		Object[] arguments = new Object[] { map };
		String rs = HproseClinetService.synCall(
				APIConstants.CSMI_ADDCUTTERSPECSINTERVAL, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderText(rs);
	}

	/**
	 * 查询使用寿命区间
	 * 
	 * 2016年7月15日 下午5:10:19
	 * 
	 * @auth liqi
	 */
	public static void getCutterSpecsInterval() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("material_id", params.get("material_id"));
		Object[] arguments = new Object[] { map };
		String rs = HproseClinetService.synCall(
				APIConstants.CSMI_GETCUTTERSPECSINTERVAL, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderText(rs);
	}

	/**
	 * 根据项目id查询项目下刀具规格
	 * 
	 * 2016年7月25日 下午4:47:33
	 * 
	 * @auth liqi
	 */
	public static void getCutterSpecsListByProjectId() {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject cutterspescs = new JSONObject();
		map.put("customer_id", UserBis.currUser());
		map.put("project_id", params.get("project_id"));
		Object[] arguments = new Object[] { map };
		String res = HproseClinetService.synCall(
				APIConstants.CSMI_GETCUTTERSPECSBYPROJECTID, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		cutterspescs = JSONObject.parseObject(res);
		JSONArray cutterspescArr = cutterspescs.getJSONArray("data");
		for (int i = 0; i < cutterspescArr.size(); i++) {
			JSONObject cutter = cutterspescArr.getJSONObject(i);
			cutter.put("id", cutter.get("material_id"));
			if(cutter.getString("status").equals("0")){
			cutter.put("value", cutter.get("customer_specs_no")+"/"+cutter.getString("long_specs_cust"));
			}else{
				cutter.put("value", cutter.get("customer_specs_no")+"/"+cutter.getString("long_specs_cust")+"(未启用)");

			}
		}
		renderJSON(cutterspescs);
	}

	public static void addRecoveryRecord() {
		String res = "";
		Map<String, Object> useNumParam = new HashMap<String, Object>();
		Object[] arguments = new Object[] { useNumParam };
		useNumParam.put("customer_id", UserBis.currUser());
		useNumParam.put("date", DateUtils.getCurrentDateTimeSimple());
		useNumParam.put("isPage", Constants.DATAISPAGE_NO);
		String cutterspesc = HproseClinetService.synCall(
				APIConstants.CSMI_GETCUTTERSPECS, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject projects = JSONObject
				.parseObject(HproseClinetService.synCall(
						APIConstants.PJMSI_GETPROJECT, arguments,
						APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
		String operatorRes = HproseClinetService.synCall(
				APIConstants.OMSI_GETOPERATOR, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject operators = JSONObject.parseObject(operatorRes);
		String machineRes = HproseClinetService.synCall(
				APIConstants.MMI_GETMACHINELIST, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject machines = JSONObject.parseObject(machineRes);
		Logger.info("cutterspecs-->" + cutterspesc);
		if ("服务不可用".equals(res) || "服务不可用".equals(cutterspesc)) {
			renderArgs.put("error", "-1");
			LoginAction.login();
		}
		JSONObject custCutters = JSONObject.parseObject(cutterspesc);
		render(custCutters, projects,
				operators, machines);
	}

	public static void addRecRecordDo() {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		JSONArray arr = new JSONArray();
		JSONObject obj = new JSONObject();
		String res = "";
		if (params.get("rec_status").equals("1")) {
			obj.put("time", DateUtils.getCurrentTimeStamp());
			obj.put("material_id", params.get("material_id").split("/")[0]);
			obj.put("process_id", params.get("material_id").split("/")[1]);
			obj.put("bag_type", params.get("bag_type"));
			obj.put("rec_status", params.get("rec_status"));
			obj.put("rec_time", DateUtils.getCurrentTimeStamp());
			obj.put("cutter_sn", "");
			obj.put("mccount", "0");
			obj.put("num", "1");
			obj.put("rec_status", params.get("rec_status"));
			obj.put("rec_desc", params.get("rec_desc"));
			obj.put("cutter_life", params.get("cutter_life"));
			obj.put("machine_id", params.get("machine_id"));
			map.put("pr_id", UserBis.currUser());
			map.put("pro_id", params.get("project_id"));
			map.put("user_id", params.get("operator_id"));
			arr.add(obj);
			map.put("rec_data", arr);
			res = HproseClinetService.synCall(APIConstants.RRMSI_ADDRECORD,
					arguments, APIConstants.CUSTOMER_HOST,
					APIConstants.CUSTOMER_PORT);
			LogsUtils.addLogs(Constants.LOG_TYPE_ADD,Convert.convertToInt(UserBis.currOperatorId(),-1), 1, "回收旧刀操作执行","success", UserBis.currLoginAccount(), UserBis.currUserName(), UserBis.currUser());
		} else if (params.get("rec_status").equals("2")) {
			obj.put("boxId", "");
			obj.put("position", "");
			obj.put("num", -1);
			obj.put("classes_id","");
			obj.put("process_id", params.get("material_id").split("/")[1]);
			obj.put("use_time", DateUtils.getCurrentTimeStamp());
			obj.put("userId", params.get("operator_id"));
			obj.put("group_id", "");
			obj.put("pro_id",params.get("project_id"));
			obj.put("material_id", params.get("material_id").split("/")[0]);
			obj.put("machine_id", params.get("machine_id"));
			obj.put("specs", "");
			arr.add(obj);
			map.put("use_data", arr);
			map.put("pr_id", UserBis.currUser());
			map.put("pro_id", params.get("project_id"));
			map.put("user_id", params.get("operator_id"));
			res = HproseClinetService.synCall(APIConstants.URMI_ADDRECORD,
					arguments, APIConstants.CUSTOMER_HOST,
					APIConstants.CUSTOMER_PORT);
			LogsUtils.addLogs(Constants.LOG_TYPE_ADD,Convert.convertToInt(UserBis.currOperatorId(),-1), 1, "回收新刀操作执行","success", UserBis.currLoginAccount(), UserBis.currUserName(), UserBis.currUser());

		}
		renderJSON(res);
	}

	public static void getOperatorProjectCutterDetail() {
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("operator_id", params.get("operator_id"));
		map.put("customer_id", UserBis.currUser());
		JSONObject data = JSONObject.parseObject(HproseClinetService.synCall(
				APIConstants.URMI_GETOPERATORPROJECTCUTTERDETAILS, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT));
		renderJSON(data);
	}
	
	public static void getProjectCutterCostRecord(){
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[] { map };
		map.put("customer_id",UserBis.currUser());
		map.put("start_date", params.get("start_date"));
		map.put("end_date", params.get("end_date"));
		map.put("project_id",params.get("project_id"));
		map.put("priceJSON", params.get("priceJSON"));
		String res = HproseClinetService.synCall(
				APIConstants.SMSI_PROJECTCUTTERCOSTSTATISTICS, arguments,
				APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject json = JSONObject.parseObject(res);
		renderJSON(json);
	}
	
}
